package com.aier.controller.purchase;


import com.aier.bean.common.CommonResult;
import com.aier.bean.inventory.InventoryRecordsBean;
import com.aier.bean.purchase.PurchaseExcelBean;
import com.aier.excel.FreezeRowColHandler;
import com.aier.service.purchase.PurchaseExcelService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 采购controller
 */

@Controller
public class PurchaseExcelController {

    @Resource
    private PurchaseExcelService purchaseExcelService;

    @RequestMapping("/download_purchase_excel")
    public void downPurchaseExcel(HttpServletResponse response){
        ExcelWriter excelWriter = null;
        try {
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("11", "UTF-8").replaceAll("\\+", "%20");
            Map<String, List<PurchaseExcelBean>> recordsTableMap = purchaseExcelService.buildPurchaseInfoExcel();
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里 需要指定写用哪个class去写
            excelWriter = EasyExcel.write(response.getOutputStream(),PurchaseExcelBean.class).build();
            int index = 0;
            for (Map.Entry<String, List<PurchaseExcelBean>> entry : recordsTableMap.entrySet()) {
                // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样
                WriteSheet writeSheet = EasyExcel.writerSheet(index, entry.getKey())
                        .registerWriteHandler(new FreezeRowColHandler(0,1,0,1))
                        .build();

                excelWriter.write(entry.getValue(), writeSheet);
                index++;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (excelWriter != null){
                excelWriter.finish();
            }
        }
    }

    @RequestMapping("/end_order")
    @ResponseBody
    public CommonResult endProduct(@RequestBody Map<String,String> map){
        String contractCode = map.get("contractCode");
        return purchaseExcelService.endContractCode(contractCode);
    }
}
